<template>
  <el-dialog
    v-model="dialogVisible"
    title="新增/修改"
    width="480px"
    :before-close="handleClose"
    append-to-body
    destroy-on-close
  >
    <el-form
      label-position="right"
      label-width="80px"
      :model="formModel"
      ref="formInsRef"
      :rules="rules"
    >
      <el-row :gutter="12">
        <el-col :span="24">
          <el-form-item label="角色名称" prop="label">
            <el-input
              v-model="formModel.label"
              placeholder="请输入"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="角色值" prop="value">
            <el-input
              v-model="formModel.value"
              placeholder="请输入"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="授权菜单">
            <el-tree
              style="max-width: 100%"
              placeholder="请选择"
              :data="menuTree"
              show-checkbox
              clearable
              node-key="value"
              ref="menuRef"
              :props="{
                children: 'children',
                label: 'label',
              }"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="onSubmit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="js" setup>
import { setModel, omit, delayFn } from "@/utils"
import { ref, reactive, onMounted } from "vue"
import { roleUpsertApi, roleAddApi } from "@/api/role"
import { ElMessage } from "element-plus"
// import { roleMenuUpsertApi } from "@/api/system"
import { menuTreeApi } from "@/api/menu"
import { useSystemStore } from "@/stores"

const systemStore = useSystemStore()
const menuRef = ref()
const menuTree = ref([])
const emits = defineEmits(["success"])
const dialogVisible = ref(false)
const data = ref()
const formInsRef = ref()
const formModel = reactive({
  id: "",
  label: "",
  value: "",
})

const rules = reactive({
  label: [{ required: true, message: "请输入" }],
  value: [{ required: true, message: "请输入" }],
})

const handleClose = () => {
  // done?.()
  formInsRef.value?.resetFields()
  dialogVisible.value = false
}

const loadMenuTree = async () => {
  const data = await menuTreeApi()
  menuTree.value = data
}

const open = async ({ row } = {}) => {
  Object.assign(formModel, setModel(formModel, row))
  data.value = row
  dialogVisible.value = true

  await delayFn()
  const selectedMenuId = row?.menus?.map((item) => item?.id) || [];
  // selectedMenuId?.forEach((item) => {
  // // 遍历去掉不需要选中的值
  //   menuRef.value.setChecked(item, true)
  // })
  menuRef.value.setCheckedKeys(selectedMenuId, true)
  await delayFn()
  // 获取树中所有选中的值
  const defaultCheckAll = menuRef.value?.getCheckedKeys() || [];
  // 通过对比树所有选中的值（defaultCheckAll）和详情返回选中的值（res.data.menuIdDtos）去取两个数组的差集
  defaultCheckAll?.filter(item => !selectedMenuId?.includes(item))?.forEach((item) => {
  // 遍历去掉不需要选中的值
    menuRef.value.setChecked(item, false)
  })
}

const buildParams = (params = {}) => {
  const postParams = {
    ...params,
    ...formModel,
    menuIds: [
      ...menuRef.value.getCheckedKeys(),
      ...menuRef.value.getHalfCheckedKeys(),
    ],
  }
  return postParams
}

const submitHandler = async () => {
  const params = buildParams()
  let res = { id: params?.id };
  if (params?.id) {
    await roleUpsertApi(params)
  } else {
    res = await roleAddApi(omit(params, ["id"]))
  }
  ElMessage.success("操作成功")
  emits("success")
  return res
}

const onClose = () => {}

const onSubmit = () => {
  if (!formInsRef.value) return
  formInsRef.value.validate(async valid => {
    if (valid) {
      const res = await submitHandler()
      // await roleMenuUpsertApi({
      //   roleId: res?.id,
      //   menuIds: [
      //     ...menuRef.value.getCheckedKeys(),
      //     ...menuRef.value.getHalfCheckedKeys(),
      //   ],
      // })
      await systemStore.reloadMenu(res?.id)
      handleClose()
      emits("success")
    } else {
      console.log("error submit!")
    }
  })
}

onMounted(() => {
  loadMenuTree()
})

defineExpose({
  open,
})
</script>
